package com.wlyuan.open.scanner.application.handler.table;

import com.alibaba.fastjson.JSON;
import com.wlyuan.open.scanner.application.annotation.TableScannerName;
import com.wlyuan.open.scanner.constant.TableEnum;
import com.wlyuan.open.scanner.repository.OrderRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author lijing
 * @description
 */
@Slf4j
@Service
@RequiredArgsConstructor
@TableScannerName(isDefault = false, tableName = {TableEnum.ATTACH, TableEnum.ADDITION})
public class OrderOtherTableToIncrHandler extends BaseTableToIncrHandler {
    private final OrderRepository orderRepository;
    private static final String ATTACH_OWNER_ID = "Attach_OwnerID";
    private static final String TRANSPORT_ORDER_ID = "Transport_OrderId";

    @Override
    public List<String> handler(String tableName, String data, String beforeData) {

        var businessParams = params(tableName, data);

        if (StringUtils.isBlank(businessParams)) {
            logger.error("{}表业务分流参数不能为空", tableName);
            return Collections.emptyList();
        }
        //根据订单id查询所属订单类型
        var srcClass = orderRepository.getOrderSrcClass(Long.valueOf(businessParams));
        if (srcClass == null) {
            logger.error("{}表订单{}所属订单类型为空", tableName, businessParams);
            return Collections.emptyList();
        }
        return buildOrderName(srcClass);
    }

    private String params(String tableName, String data) {
        //附件,多段轨迹 主表为 订单表 businessParams 为所属订单id
        var map = JSON.parseObject(data, Map.class);
        var businessParams = "";
        if (TableEnum.ATTACH.getVal().equals(tableName)) {
            businessParams = String.valueOf(map.get(ATTACH_OWNER_ID));
        }
        if (TableEnum.ADDITION.getVal().equals(tableName)) {
            businessParams = String.valueOf(map.get(TRANSPORT_ORDER_ID));
        }
        return businessParams;
    }
}
